//
//  UDSettingPhotoTools.m
//  MFI_Udisk
//
//  Created by chenyongsheng on 15/8/6.
//  Copyright (c) 2015年 Jim Mao. All rights reserved.
//

#import "UDAlumbPhotoTools.h"
#import "UDAssetInfo.h"
#import "UDPhotoGroupInfo.h"
#import <AssetsLibrary/AssetsLibrary.h>
@interface UDAlumbPhotoTools()
{
    BOOL _isComplateAcquireGroup;
    NSInteger _groupNum;
}
@property (nonatomic,strong) ALAssetsLibrary *library;
@property (nonatomic,strong) NSMutableArray *groupArr;

@end

@implementation UDAlumbPhotoTools
static UDAlumbPhotoTools *onceObject = nil;
+ (instancetype)share
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        onceObject = [[super alloc] init];
    });
    return onceObject;
}
- (instancetype)init
{
    if (self = [super init])
    {
        self.groupArr = [NSMutableArray array];
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(__receiveMemoryWarning) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    }
    return self;
}
- (void)__receiveMemoryWarning
{
    
}
/**
 *  为了准确判断所有分组信息获取完成
 */
- (void)acquirePhotoLibraryGroupsWithComplateBlock:(void(^)(BOOL isSucess,id result))block
{
    
    [_groupArr removeAllObjects];
    
    ALAssetsLibraryAccessFailureBlock failBlock = ^(NSError *failError)
    {
        if ([failError.localizedDescription rangeOfString:@"Global denied access"].location!=NSNotFound)
        {
            block(NO, @"Backup failed because you refuse to access the album");
        }
        else
        {
            block(NO, @"Backup failed because you refuse to access the album");
        }
    };
    _isComplateAcquireGroup = NO;
    _groupNum = 0;
    ALAssetsLibraryGroupsEnumerationResultsBlock
    libraryGroupsEnumeration = ^(ALAssetsGroup* group,BOOL* stop)
    {
        
        if (group == nil)
        {
            _isComplateAcquireGroup = YES;
            if (_groupArr.count == _groupNum)
            {
                block(YES,[NSArray arrayWithArray:_groupArr]);
            }
        }
        if (group!=nil)
        {
            
            _groupNum++;
            [self exchangeInfoThroughGroup:group withComplateBlock:^(UDPhotoGroupInfo *myGroup) {
                [_groupArr addObject:myGroup];
                if (_isComplateAcquireGroup && (_groupNum == _groupArr.count))
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        block(YES,[NSArray arrayWithArray:_groupArr]);
                    });
                }
            }];
        }
        
    };
    
    self.library = [[ALAssetsLibrary alloc] init];
    [_library enumerateGroupsWithTypes:ALAssetsGroupAll
                           usingBlock:libraryGroupsEnumeration
                         failureBlock:failBlock];

}
- (void)exchangeInfoThroughGroup:(ALAssetsGroup *)group withComplateBlock:(void(^)(UDPhotoGroupInfo *myGroup))block
{
    UDPhotoGroupInfo *privateGroup = [[UDPhotoGroupInfo alloc] init];
    privateGroup.groupName = [group valueForProperty:ALAssetsGroupPropertyName];
    [group setAssetsFilter:[ALAssetsFilter allAssets]];
    [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
        
        if (result == nil)
        {
            block(privateGroup);
        }
        if (result != nil)
        {
            NSString *imageName = [[result defaultRepresentation] filename];
            UDAssetInfo *assetInfo = [[UDAssetInfo alloc] init];
            assetInfo.groupName = privateGroup.groupName;
            assetInfo.assetName = imageName;
            assetInfo.asset = result;
            
            NSString *type =  [result valueForProperty:ALAssetPropertyType];
            
            if ([type compare:ALAssetTypePhoto] == NSOrderedSame)
            {
                assetInfo.assetSize = [[result defaultRepresentation] size];//获得资源大小是费时的操作
                assetInfo.assetType = UDPhotoAsset;
                NSMutableArray *photoArr = [privateGroup.groupAssetInfoDic objectForKey:assetPhotoKey];
                if (photoArr)
                {
                    [photoArr addObject:assetInfo];
                }else
                {
                    NSMutableArray *photoArr = [NSMutableArray arrayWithObject:assetInfo];
                    [privateGroup.groupAssetInfoDic setObject:photoArr forKey:assetPhotoKey];
                }
                
            }
            if ([type compare:ALAssetTypeVideo] == NSOrderedSame)
            {
                assetInfo.assetSize = [[result defaultRepresentation] size];
                assetInfo.assetType = UDMovieAsset;
                NSMutableArray *movieArr = [privateGroup.groupAssetInfoDic objectForKey:assetMovieKey];
                if (movieArr)
                {
                    [movieArr addObject:assetInfo];
                }else
                {
                    NSMutableArray *movieArr = [NSMutableArray arrayWithObject:assetInfo];
                    [privateGroup.groupAssetInfoDic setObject:movieArr forKey:assetMovieKey];
                }
            }
            if ([type compare:ALAssetTypeUnknown] == NSOrderedSame)
            {
                
            }
        }
    }];
}

- (NSArray *)alumbFiles
{
    return [NSArray arrayWithArray:_groupArr];
}
@end
